<?php

include_once("config.php");

class logging {
    private static $instance = null;
    private $fp = null;

    private function __construct() {
        if (PHP_SAPI != "cli") {
            if (!is_dir(LOG_DIR)) {
                mkdir(LOG_DIR, 0777, true);
            }
            $path = LOG_DIR . "/logging-" . date("Y-m-d") . ".log";
            if (!file_exists($path)) {
                touch($path);
            }
            $this->fp = fopen($path, "a");
        }
    }

    private static function instance() {
        if (self::$instance == null) {
            self::$instance = new logging();
        }
        return self::$instance;
    }

    private function write($level, $tag, $message) {
        if (PHP_SAPI != "cli") {
            if (!$this->fp) {
                return false;
            }
        }

        $currentTime = gettimeofday();
        $ms = $currentTime["usec"];
        $ms = sprintf("%03d", (int) $ms / 1000);
        $tag = sprintf("%-8s", $tag);

        $logs = "<" . date("Y-m-d H:i:s") . ":$ms> ";
        // $logs .= isset($_SESSION['username']) ? "user:{$_SESSION['username']}" : "user:not login";
        $logs .= "    [";
        $logs .= isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'shell';
        $logs .= "]";
        // $logs .= "    (";
        // $logs .= isset($_SESSION["username"]) ? ($_SESSION["username"] . "|" . $_SESSION["mail"]) : "NOT LOGIN";
        // $logs .= ")";
        $logs .= "    $level/$tag    $message\n";

        if (PHP_SAPI == "cli") {
            printf("%s", $logs);
        } else {
            flock($this->fp, LOCK_EX);
            fwrite($this->fp, $logs);
            flock($this->fp, LOCK_UN);
        }
        return true;
    }

    public static function d($tag, $message) {
        logging::instance()->write("D", $tag, $message);
    }

    public static function e($tag, $message) {
        logging::instance()->write("E", $tag, $message);
    }

    public static function i($tag, $message) {
        logging::instance()->write("I", $tag, $message);
    }

    public static function v($tag, $message) {
        logging::instance()->write("V", $tag, $message);
    }

}

// -- logging::d("TEST", "saaaaadsfasfdsadf");
// -- logging::i("TEST", "saaaaadsfasfdsadf");
// -- logging::e("TEST", "saaaaadsfasfdsadf");
// -- logging::v("TEST", "saaaaadsfasfdsadf");







